
package com.chao.tlias.interceptor;

import com.chao.tlias.util.CurrentHolder;
import com.chao.tlias.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


/**
 * 使用拦截器进行token校验
 */

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求Url
        String requestURI = request.getRequestURI();

        //2.判断请求Url是否包含login，如果包含则放行
        if (requestURI.contains("login")){
            log.info("本次请求是登录操作，放行....");
            return true;
        }

        //3.从请求头中获取令牌（token）
        String token = request.getHeader("token");

        //4.判断令牌是否存在，如果不存在，响应401
        if (token==null||token.isEmpty()){
            log.info("令牌为空，返回401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //5.令牌存在，解析token，如果解析失败，响应401
        try {
            Claims claims = JwtUtils.parseToken(token);
            Integer empid = (Integer) claims.get("id");//从token 中获取ID
            CurrentHolder.setCurrent(empid);//将token中的ID存入当前线程中
            log.info("登录用户的id为：{}", empid+"已经存入当前线程");
        } catch (Exception e) {
            log.info("令牌错误，返回401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //6.校验通过，放行
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentHolder.remove();//执行完后， 移除当前线程存入的内容
    }
}

